//
//  QueryViewController.m
//  Audit
//
//  Created by cc on 15-3-3.
//  Copyright (c) 2015年 cc. All rights reserved.
//

#import "QueryViewController.h"
#import "UIScrollView+SVInfiniteScrolling.h"
#import "UIScrollView+SVPullToRefresh.h"
#import "CarCell.h"
#import "DefectCell.h"
#import "AppDelegate.h"
#import "AddCarViewController.h"
#import "AddDefectViewController.h"
#import "ConditionViewController.h"
#import "GetVinViewController.h"
#import "CarDetailViewController.h"
#import "DefectDetailViewController.h"


typedef NS_ENUM(NSUInteger, QueryStatus)
{
    QueryStatusQuickQuery =0,
    QueryStatusAdvancedQuery = 1
};

typedef NS_ENUM(NSUInteger, QueryViewStatus)
{
    QueryViewStatusCustom =0,
    QueryViewStatusTop = 1//上面
};

@interface QueryViewController ()<UITableViewDataSource,LCSwipeTableViewCellDelegate,UITableViewDelegate,UITextFieldDelegate>
{
    
    IBOutlet UIView *_quickQueryView;
    IBOutlet UIView *_advancedQueryView;
    IBOutlet UIView *_topAddDefectView;
    
    QueryStatus _queryStatus;
    QueryViewStatus _queryViewStatus;
    
    IBOutlet UIView *_guideView;
    IBOutlet UIButton *_backToListBtn;//返回到列表按钮
    
    
}
@property(nonatomic,retain) IBOutlet UITableView *carsTableView;
@property(nonatomic,retain) IBOutlet UITableView *defectTableView;
//@property (nonatomic, assign) NSInteger currentPage;
//@property(nonatomic,retain) NSMutableArray *tableDataList;//数据
//@property(nonatomic,retain) NSMutableArray *defectDataList;//数据
@end

@implementation QueryViewController

//-(void)dealloc
//{
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:NOTIFICATION_INIT_SEARCH_DATA object:nil];
//    
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:NOTIFICATION_CHOOSE_CONDITION_ACTION object:nil];
//}

- (void)viewDidLoad {
    [super viewDidLoad];

    _backToListBtn.hidden = YES;
    
    [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(setInitSearchData) name:NOTIFICATION_INIT_SEARCH_DATA object:nil];//加载数据完成后初始化控件
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(alertList) name:NOTIFICATION_CHOOSE_CONDITION_ACTION object:nil];//加载完成数据后弹出选择列表
    
    //使用NSNotificationCenter 鍵盤出現時
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWasShown:)
                                                 name:UIKeyboardDidShowNotification object:nil];
    
    //使用NSNotificationCenter 鍵盤隐藏時
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillBeHidden:)
                                                 name:UIKeyboardWillHideNotification object:nil];
    
    self.isAlertList = NO;
    
    CGRect quickRect = _quickQueryView.frame;
    quickRect.origin.x = 0;
    quickRect.origin.y =50;
    _quickQueryView.frame = quickRect;
    
    CGRect advancedRect = _advancedQueryView.frame;
    advancedRect.origin.x = 0;
    advancedRect.origin.y = 50;
    _advancedQueryView.frame = advancedRect;
    
    btnSeries.tag=1001;
    btnModel.tag=1002;
    btnPlant.tag=1003;
    btnDomain.tag=1004;
    btnAuditGroup.tag=1005;
    btnPhase.tag=1008;
    
    btnModelQuick.tag = 1009;
    
    txtBuildDate.returnKeyType = UIReturnKeyNext;
    txtColor.returnKeyType = UIReturnKeyNext;
    txtCsn.returnKeyType = UIReturnKeyNext;
    txtDefect_Info.returnKeyType = UIReturnKeyNext;
    txtDriveDirection.returnKeyType = UIReturnKeyNext;
    txtEngine.returnKeyType = UIReturnKeyNext;
    txtRepair_Info.returnKeyType = UIReturnKeyNext;
    txtShiftDate.returnKeyType = UIReturnKeyNext;
    txtTransmission.returnKeyType = UIReturnKeyNext;
    txtVin.returnKeyType = UIReturnKeyNext;
    
    textFieldVIN.returnKeyType = UIReturnKeyNext;
    textFieldCsn.returnKeyType = UIReturnKeyNext;
    
    txtBuildDate.delegate = (id<UITextFieldDelegate>)self;
    txtColor.delegate = (id<UITextFieldDelegate>)self;
    txtCsn.delegate = (id<UITextFieldDelegate>)self;
    txtDefect_Info.delegate = (id<UITextFieldDelegate>)self;
    txtDriveDirection.delegate = (id<UITextFieldDelegate>)self;
    txtEngine.delegate = (id<UITextFieldDelegate>)self;
    txtRepair_Info.delegate = (id<UITextFieldDelegate>)self;
    txtShiftDate.delegate = (id<UITextFieldDelegate>)self;
    txtTransmission.delegate = (id<UITextFieldDelegate>)self;
    txtVin.delegate = (id<UITextFieldDelegate>)self;
    
    textFieldVIN.delegate = (id<UITextFieldDelegate>)self;
    textFieldCsn.delegate = (id<UITextFieldDelegate>)self;

    if (_queryStatus == QueryStatusQuickQuery) {
        [self.view addSubview:_quickQueryView];
        
    }else{
        [self.view addSubview:_advancedQueryView];
    }
    
    self.carsTableView.delegate = self;
    self.defectTableView.delegate = self;
    
    [textFieldVIN addTarget:self action:@selector(textChange:) forControlEvents:UIControlEventEditingChanged];
    
    [txtVin addTarget:self action:@selector(textChange:) forControlEvents:UIControlEventEditingChanged];
    
    self.carConditionQuick = [[Car alloc] init];
    self.carConditionQuery = [[Car alloc] init];
    
    self.carConditionQuick.model = @"";
    
    self.carConditionQuery.model = @"";
    self.carConditionQuery.plant = @"";
    self.carConditionQuery.domain = @"";
    self.carConditionQuery.auditGroup = @"";
    self.carConditionQuery.series = @"";
    self.carConditionQuery.phase = @"";
    
    self.isLoadListData = NO;
    
    [self getListData];
    
    self.datePick1      = [[UIDatePicker alloc] init];
    self.datePick1.datePickerMode = UIDatePickerModeDate;
    
    self.datePick2      = [[UIDatePicker alloc] init];
    self.datePick2.datePickerMode = UIDatePickerModeDate;
    
    txtShiftDate.delegate = (id<UITextFieldDelegate>)self;
    txtShiftDate.inputView = self.datePick1;
    
    txtBuildDate.delegate = (id<UITextFieldDelegate>)self;
    txtBuildDate.inputView = self.datePick2;
    
    [self.datePick1 addTarget:self action:@selector(dateDidPicker:) forControlEvents:UIControlEventValueChanged];
    
    [self.datePick2 addTarget:self action:@selector(dateDidPicker:) forControlEvents:UIControlEventValueChanged];
    
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"yyyy-MM-dd"];

    txtShiftDate.text = [NSString stringWithFormat:@"%@",[dateformatter stringFromDate:[NSDate date]]];
    txtBuildDate.text = [NSString stringWithFormat:@"%@",[dateformatter stringFromDate:[NSDate date]]];
    
    
    _topAddDefectView.frame = CGRectMake(0, -_topAddDefectView.frame.size.height, self.defectTableView.frame.size.width, _topAddDefectView.frame.size.height);
    [self.defectTableView addSubview:_topAddDefectView];
}

-(void)dateDidPicker:(id)sender
{
    UIDatePicker *datePick = (UIDatePicker *)sender==self.datePick1?self.datePick1:self.datePick2;
    
    NSDate * senddate=[datePick date];
    
//    NSCalendar *calendar = [ NSCalendar currentCalendar ];
//    
//    int unit = NSCalendarUnitDay | NSCalendarUnitMonth |  NSCalendarUnitYear ;
//    
//    NSDateComponents *plusdays=[calendar components :unit fromDate : [datePick date] toDate :[ NSDate date ] options : 0 ];
//    
//    if (!(plusdays.year>0||plusdays.month>0||plusdays.day>0))
//    {
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"yyyy-MM-dd"];
    
    if (datePick==self.datePick1) {
        txtShiftDate.text=[NSString stringWithFormat:@"%@",[dateformatter stringFromDate:senddate]];
    }
    else
    {
        txtBuildDate.text=[NSString stringWithFormat:@"%@",[dateformatter stringFromDate:senddate]];
    }
//    }
}

//获取列表数据
-(void)getListData
{
    AppDelegate *delegate=(AppDelegate*)[[UIApplication sharedApplication] delegate];
    
    if (!delegate.isLoadCarList) {
        delegate.isNoNetWork=NO;
        [self getCarList];
        
//        [self setInitSearchData];
    }
    else
    {
        [self setInitSearchData];
    }
    
//    dispatch_async(dispatch_get_global_queue(0, 0), ^{
//        while (1) {
//            [NSThread sleepForTimeInterval:0.05];
//            
//            if (delegate.isLoadCarList)
//            {
//                dispatch_async(dispatch_get_main_queue(),^{
//                    [self setInitSearchData];
//                });
//                break;
//            }
//            else if (delegate.isNoNetWork)
//            {
//                break;
//            }
//        }
//    });

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(NSString *)changeNilToStr:(NSString *)str
{
    return str?str:@"";
}

-(void)loadMoreData
{
    NSMutableArray *valueArr = [NSMutableArray array];
    
    if (_queryStatus == QueryStatusAdvancedQuery) {
        valueArr = [NSMutableArray arrayWithObjects:[self changeNilToStr:self.carConditionQuery.vin],[self changeNilToStr:self.carConditionQuery.model],[self changeNilToStr:self.carConditionQuery.csn],[self changeNilToStr:self.carConditionQuery.plant],[self changeNilToStr:self.carConditionQuery.domain],[self changeNilToStr:self.carConditionQuery.auditGroup],[self changeNilToStr:self.carConditionQuery.shiftDate],[self changeNilToStr:self.carConditionQuery.buildDate],[self changeNilToStr:self.carConditionQuery.series],[self changeNilToStr:self.carConditionQuery.phase],[self changeNilToStr:self.carConditionQuery.engine],[self changeNilToStr:self.carConditionQuery.transmission],[self changeNilToStr:self.carConditionQuery.color],[self changeNilToStr:self.carConditionQuery.drivedirection],[self changeNilToStr:self.carConditionQuery.defect_info],[self changeNilToStr:self.carConditionQuery.repair_info], nil];
    }
    else if (_queryStatus == QueryStatusQuickQuery)
    {
         valueArr = [NSMutableArray arrayWithObjects:[self changeNilToStr:self.carConditionQuick.vin],[self changeNilToStr:self.carConditionQuick.model],[self changeNilToStr:self.carConditionQuick.csn], nil];
    }
    
    NSMutableArray *keyArr;
    
    if (valueArr.count==3) {
        keyArr   = [NSMutableArray arrayWithObjects:@"vin",@"modelList",@"csn", nil];
    }
    else
    {
        keyArr   = [NSMutableArray arrayWithObjects:@"vin",@"modelList",@"csn",@"plantList",@"domainList",@"auditGroupList",@"shiftDate",@"buildDate",@"seriesList",@"phaseList",@"engine",@"transmission",@"color",@"drivedirection",@"defect_info",@"repair_info", nil];
    }
    
    
    [valueArr addObject:@"10"];
    [keyArr   addObject:@"pageSize"];
    
    [valueArr addObject:[NSString stringWithFormat:@"%ld",(long)self.currentPage * 10 ]];
    [keyArr   addObject:@"currentIndex"];
    
    [gAlert showLoading:nil delegate:nil];
    
    
    [CommunicateWithService communicateWithService:keyArr value:valueArr apiName:@"queryVhc.do" finishSelector:@selector(QueryCarFinished:) failSelector:@selector(QueryCarFailed:) delegateObj:self];
}

-(void)QueryCarFinished:(ASIHTTPRequest *)request
{
    [gAlert dismiss];
    if (request.responseStatusCode == 400) {
        //textView.text = @"Invalid code";
        NSLog(@"Invalid code");
    } else if (request.responseStatusCode == 403) {
        NSLog(@"Code already used");
        //textView.text = @"Code already used";
    } else if (request.responseStatusCode == 200) {
        NSDictionary *strDic=[CommunicateWithService getDataDic:request.responseString];//解析json 2 dic
        
//        NSLog(@"%@",request.responseString);
        
        NSString *flag=[strDic objectForKey:@"resultCode"];//服务器返回代码
        
        NSString *msg=[strDic objectForKey:@"resultValue"];//服务器返回提示消息
        
        NSDictionary *strDicData=(NSDictionary *)[strDic objectForKey:@"resultData"];//服务器返回数据字典
        
        //        self.tableDataList = [NSMutableArray array];
        
        if ([flag isEqualToString:@"1001"]) {
            NSArray *carList = [strDicData objectForKey:@"content"];
            
            self.pageCount = [[strDicData objectForKey:@"countPage"] integerValue];
            
            __weak __typeof(&*self)weakSelf = self;
            
            [weakSelf.carsTableView.pullToRefreshView stopAnimating];
            [weakSelf.carsTableView.infiniteScrollingView stopAnimating];
            
            for (int i = 0; i < carList.count; i++) {
                Car *carobj = [[Car alloc] initWithInfo:(NSDictionary *)[carList objectAtIndex:i]];
                
                [self.listCar addObject:carobj];
            }
            
            [self.carsTableView reloadData];
            
            if (self.listCar.count>0)
            {
                self.selectedCar = [[Car alloc] init];
                
//                NSMutableArray *keyArr=[NSMutableArray array];
//                NSMutableArray *valueArr=[NSMutableArray array];
                
                NSMutableArray *keyArr = [NSMutableArray arrayWithObjects:@"vehicleId" , nil];
                NSMutableArray *valueArr = [NSMutableArray arrayWithObjects:((Car *)[self.listCar objectAtIndex:0]).vehicleId , nil];
                
                self.selectedCar = (Car *)[self.listCar objectAtIndex:0];
                
                [_carsTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]  animated:NO scrollPosition:UITableViewScrollPositionTop];
                
                [gAlert showLoading:nil delegate:nil];
                
                [CommunicateWithService communicateWithService:keyArr value:valueArr apiName:@"queryVhcDefect.do" finishSelector:@selector(QueryDefectFinished:) failSelector:@selector(QueryDefectFailed:) delegateObj:self];
                
                if (weakSelf.pageCount > weakSelf.currentPage + 1) {
                    [self.carsTableView addInfiniteScrollingWithActionHandler:^{
                        //                    weakSelf.isShowHUD = NO;
                        weakSelf.currentPage++;
                        [weakSelf loadMoreData];
                    }];
                }
                else
                {
                    weakSelf.carsTableView.showsInfiniteScrolling = NO;
                }
            }
            else
            {
                self.selectedCar.listDefect = nil;
                
                self.selectedCar = nil;
                
                [_defectTableView reloadData];
                
                [gAlert show:@"没有车辆数据噢" inView:self.view delegate:nil];
            }
        }
        else if ([flag isEqualToString:@"1002"])
        {
            
            [gAlert show:msg inView:self.view delegate:nil];
        }
    }
}

-(void)QueryCarFailed:(ASIHTTPRequest *)request
{
    [gAlert dismiss];
//    [self hideWaitFromView:self.view animated:YES];
    [NetworkCheck checkNetwork:self];
    
    __weak __typeof(&*self)weakSelf = self;
    [weakSelf.carsTableView.pullToRefreshView stopAnimating];
    [weakSelf.carsTableView.infiniteScrollingView stopAnimating];
}

-(void)QueryDefectFinished:(ASIHTTPRequest *)request
{
    [gAlert dismiss];
    if (request.responseStatusCode == 400) {
        //textView.text = @"Invalid code";
        NSLog(@"Invalid code");
    } else if (request.responseStatusCode == 403) {
        NSLog(@"Code already used");
        //textView.text = @"Code already used";
    } else if (request.responseStatusCode == 200) {
        NSDictionary *strDic=[CommunicateWithService getDataDic:request.responseString];//解析json 2 dic
        
        NSString *flag=[strDic objectForKey:@"resultCode"];//服务器返回代码
        
        NSString *msg=[strDic objectForKey:@"resultValue"];//服务器返回提示消息
        
        NSArray *strDicData=(NSArray *)[strDic objectForKey:@"resultData"];//服务器返回数据字典
        
        self.selectedCar.listDefect = [NSMutableArray array];
        
        if ([flag isEqualToString:@"1001"]) {
            for (int i = 0; i < strDicData.count; i++) {
                NSDictionary *defectDic = (NSDictionary *)[strDicData objectAtIndex:i];

                Defect *defectobj = [[Defect alloc] initWithInfo:defectDic];

//                NSMutableArray *keyArr=[NSMutableArray array];
//                NSMutableArray *valueArr=[NSMutableArray array];
                
                NSMutableArray *keyArr = [NSMutableArray arrayWithObjects:@"fileName" , @"fileLink" , nil];
                NSMutableArray *valueArr = [NSMutableArray arrayWithObjects:defectobj.fileName , defectobj.fileLink , nil];
                
                NSString *urlLogin=[NSString stringWithFormat:@"%@%@",__URL__,@"queryImageVhc.do"];
                
                NSURL *postURL=[NSURL URLWithString:urlLogin];
                
                self.asiFDR=[[ASIFormDataRequest alloc] initWithURL:postURL];
                if (valueArr.count>0) {
                    for (int i=0; i<keyArr.count; i++) {
                        [self.asiFDR setPostValue:[valueArr objectAtIndex:i] forKey:[keyArr objectAtIndex:i]];
                    }
                    [self.asiFDR setTimeOutSeconds:5.0];
                    [self.asiFDR setDelegate:self];
                    [self.asiFDR startSynchronous];
                    
                    UIImage *image=[UIImage imageWithData:[self.asiFDR responseData]];
                    
                    defectobj.uploadedFile = image;
                }

                [self.selectedCar.listDefect addObject:defectobj];
            }
            
            if (self.selectedCar.listDefect.count == 0) {
                [gAlert show:@"没有缺陷数据噢" inView:self.view delegate:nil];
            }
            
            [self.defectTableView reloadData];
        }
        else if ([flag isEqualToString:@"1002"])
        {
            [gAlert show:msg inView:self.view delegate:nil];
        }
    }
    
//    NSLog(@"%d",request.responseStatusCode);
}

-(void)QueryDefectFailed:(ASIHTTPRequest *)request
{
    [gAlert dismiss];
    [NetworkCheck checkNetwork:self];
}

-(void)QueryImageFinished:(ASIHTTPRequest *)request
{
    [gAlert dismiss];
    if (request.responseStatusCode == 400) {
        //textView.text = @"Invalid code";
        NSLog(@"Invalid code");
    } else if (request.responseStatusCode == 403) {
        NSLog(@"Code already used");
        //textView.text = @"Code already used";
    } else if (request.responseStatusCode == 200) {
        UIImage *image=[UIImage imageWithData:[request responseData]];
        
        UIImageView *test = [[UIImageView alloc] initWithImage:image];
        
        [self.view addSubview:test];
    }
}

-(void)QueryImageFailed:(ASIHTTPRequest *)request
{
    [gAlert dismiss];
    [NetworkCheck checkNetwork:self];
}

- (void)navRightButtonActionAtTag:(NSUInteger)tag
{
    //todo:返回数据
    [super backAction:nil];
}

#pragma mark- Actions
//扫描条形码获取VIN
-(IBAction)getVinStrQuick:(id)sender
{
    GetVinViewController * getVinVC = [[GetVinViewController alloc]init];//扫描条形码二维码VC
    getVinVC.doSth=@"getVIN";
    getVinVC.getVinStr=^(NSString *vinStr){
        //        NSLog(@"%@",vinStr);
        textFieldVIN.text = vinStr;
    };
    
    [self presentViewControllerInFullRect:getVinVC];
}

//扫描条形码获取VIN
-(IBAction)getVinStr:(id)sender
{
    GetVinViewController * getVinVC = [[GetVinViewController alloc]init];//扫描条形码二维码VC
    getVinVC.doSth=@"getVIN";
    getVinVC.getVinStr=^(NSString *vinStr){
//        NSLog(@"%@",vinStr);
        txtVin.text = vinStr;
    };
    
    [self presentViewControllerInFullRect:getVinVC];
}

//扫描条形码获取TPS
-(IBAction)getTPSStr:(id)sender
{
    GetVinViewController * getVinVC = [[GetVinViewController alloc]init];//扫描条形码二维码VC
    getVinVC.doSth=@"getTPS";
    getVinVC.getVinStr=^(NSString *vinStr){
//        NSLog(@"%@",vinStr);
        
        NSString *csnStr=[vinStr substringToIndex:8];
        
        txtCsn.text = csnStr;
    };
    
    [self presentViewControllerInFullRect:getVinVC];
}

-(IBAction)chooseConditionAction:(id)sender
{
    self.isAlertList = YES;
    self.btnSender = (UIButton *)sender;
    [self getListData];
}

-(void)alertList
{
    if (self.isAlertList) {
        self.isAlertList = NO;
        if (self.btnSender.tag!=1006&&self.btnSender.tag!=1007) {        ConditionViewController *vc = [[ConditionViewController alloc] init];
            vc.fromVC=@"searchcar";
            vc.naviTitle = self.btnSender.titleLabel.text;
            vc.paramsArr = [NSArray array];
            switch (self.btnSender.tag) {
                case 1001:
                    vc.paramsArr = self.arrSeriesList;
                    break;
                case 1002:
                    vc.paramsArr = self.arrModelList;
                    break;
                case 1003:
                    vc.paramsArr = self.arrPlantList;
                    break;
                case 1004:
                    vc.paramsArr = self.arrDomainList;
                    break;
                case 1005:
                    vc.paramsArr = self.arrGroupList;
                    break;
                case 1008:
                    vc.paramsArr = self.arrPhaseList;
                    break;
                case 1009:
                    vc.paramsArr = self.arrModelList;
                    break;
                default:
                    break;
            }
            
            [self presentViewControllerInSmallRect:vc];
            
            vc.setText=^(NSString *key,NSString *value)
            {
                //设置选中值
                switch (self.btnSender.tag) {
                    case 1001:
                        self.carConditionQuery.series=key;
                        self.carConditionQuery.seriesDesc=value;
                        
                        btnSeries.titleLabel.text = value;
                        break;
                    case 1002:
                        self.carConditionQuery.model=key;
                        self.carConditionQuery.modelDesc=value;
                        
                        btnModel.titleLabel.text = value;
                        break;
                    case 1003:
                        self.carConditionQuery.plant=key;
                        self.carConditionQuery.plantDesc=value;
                        
                        btnPlant.titleLabel.text = value;
                        break;
                    case 1004:
                        self.carConditionQuery.domain=key;
                        self.carConditionQuery.domainDesc=value;
                        
                        btnDomain.titleLabel.text = value;
                        break;
                    case 1005:
                        self.carConditionQuery.auditGroup=key;
                        self.carConditionQuery.auditGroupDesc=value;
                        
                        btnAuditGroup.titleLabel.text = value;
                        break;
                    case 1008:
                        self.carConditionQuery.phase=key;
                        self.carConditionQuery.phaseDesc=value;
                        
                        btnPhase.titleLabel.text = value;
                        break;
                    case 1009:
                        self.carConditionQuick.model=key;
                        self.carConditionQuick.modelDesc=value;
                        
                        btnModelQuick.titleLabel.text = value;
                        break;
                    default:
                        break;
                }
                
                [self.btnSender setTitle:value forState:UIControlStateNormal];
            };
        }
    }
}

//高级查询
//-(IBAction)advancedAction:(id)sender
//{
//    AppDelegate *delegate=(AppDelegate*)[[UIApplication sharedApplication] delegate];
//    
//    if (!delegate.isLoadCarList) {
//        delegate.isNoNetWork=NO;
//        [self getCarList];
//    }
//    
//    dispatch_async(dispatch_get_global_queue(0, 0), ^{
//        while (1) {
//            if (delegate.isLoadCarList)
//            {
//                dispatch_async(dispatch_get_main_queue(),^{
//                    [self setInitSearchData];
//                });
//                break;
//            }
//            else if (delegate.isNoNetWork)
//            {
//                break;
//            }
//        }
//    });
//    
//    _queryStatus = QueryStatusAdvancedQuery;
//    [_quickQueryView removeFromSuperview];
//    [self.view addSubview:_advancedQueryView];
//}

//数据初始化
-(void)setInitSearchData
{
    if (!self.isLoadListData) {
        NSUserDefaults *userInfo=[NSUserDefaults standardUserDefaults];
        
        self.arrDomainList = (NSMutableArray *)[userInfo arrayForKey:@"domainList"];
        self.arrGroupList  = (NSMutableArray *)[userInfo arrayForKey:@"groupList"];
        self.arrModelList  = (NSMutableArray *)[userInfo arrayForKey:@"modelList"];
        self.arrPhaseList  = (NSMutableArray *)[userInfo arrayForKey:@"phaseList"];
        self.arrPlantList  = (NSMutableArray *)[userInfo arrayForKey:@"plantList"];
        self.arrSeriesList = (NSMutableArray *)[userInfo arrayForKey:@"seriesList"];
        
        self.isLoadListData = YES;
        
        //设置btn初始值
        if ([self.carConditionQuery.series isEqualToString:@""]) {
            [btnSeries setTitle:@"不限" forState:UIControlStateNormal];
        }
        if ([self.carConditionQuery.model isEqualToString:@""]) {
            [btnModel setTitle:@"不限" forState:UIControlStateNormal];
        }
        if ([self.carConditionQuery.plant isEqualToString:@""]) {
            [btnPlant setTitle:@"不限" forState:UIControlStateNormal];
        }
        if ([self.carConditionQuery.domain isEqualToString:@""]) {
            [btnDomain setTitle:@"不限" forState:UIControlStateNormal];
        }
        if ([self.carConditionQuery.auditGroup isEqualToString:@""]) {
            [btnAuditGroup setTitle:@"不限" forState:UIControlStateNormal];
        }
        if ([self.carConditionQuery.phase isEqualToString:@""]) {
            [btnPhase setTitle:@"不限" forState:UIControlStateNormal];
        }
        
        if ([self.carConditionQuick.model isEqualToString:@""]) {
            [btnModelQuick setTitle:@"不限" forState:UIControlStateNormal];
        }
        
        [self.view setNeedsLayout];
    }
    
    [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_CHOOSE_CONDITION_ACTION object:nil];
}



////快速查询
//-(IBAction)quickAction:(id)sender
//{
//    _queryStatus = QueryStatusQuickQuery;
//    [_advancedQueryView removeFromSuperview];
//    [self.view addSubview:_quickQueryView];
//}

//查询
-(IBAction)queryAction:(id)sender
{
    [textFieldCsn resignFirstResponder];
    [textFieldVIN resignFirstResponder];
    
//    self.selectedCar.listDefect = nil;
//    
//    [_defectTableView reloadData];
//    
//    self.selectedCar = nil;
//    
//    self.listCar = nil;
//    
//    [_carsTableView reloadData];
    
    if (_queryStatus == QueryStatusQuickQuery) {
        
        //快速查
        [UIView animateWithDuration:0.5f animations:^{
            _quickQueryView.transform = CGAffineTransformMakeTranslation(0, -(_quickQueryView.frame.size.height+50));
            
        } completion:^(BOOL finished) {
            
            _queryViewStatus = QueryViewStatusTop;
            _backToListBtn.hidden = YES;
        }];
        
        Car *condition=[[Car alloc] init];
        
        condition.vin   = textFieldVIN.text;
        condition.model = self.carConditionQuick.model;
        condition.csn   = textFieldCsn.text;
        
        //todo
        self.carConditionQuick = [[Car alloc] init];
        self.carConditionQuick = condition;
        
        __weak __typeof(&*self)weakSelf = self;
        
        weakSelf.currentPage = 0;
        weakSelf.listCar = [NSMutableArray array];
        
        [self.carsTableView addPullToRefreshWithActionHandler:^{
            weakSelf.currentPage = 0;
            [weakSelf.listCar removeAllObjects];
            //todo  添加获取数据请求
            [weakSelf loadMoreData];
        }];
        [weakSelf loadMoreData];
    }else{
        
        //高级查询
        [UIView animateWithDuration:0.5f animations:^{
            _advancedQueryView.transform = CGAffineTransformMakeTranslation(0, -(_quickQueryView.frame.size.height+50));
            
        } completion:^(BOOL finished) {
            _queryViewStatus = QueryViewStatusTop;
            _backToListBtn.hidden = YES;
        }];
        
        
        Car *condition=[[Car alloc] init];
        
        condition.vin            = txtVin.text;
        condition.model          = self.carConditionQuery.model;
        condition.csn            = txtCsn.text;
        
        condition.plant          = self.carConditionQuery.plant;
        condition.domain         = self.carConditionQuery.domain;
        condition.auditGroup     = self.carConditionQuery.auditGroup;
        condition.shiftDate      = txtShiftDate.text;
        condition.buildDate      = txtBuildDate.text;
        condition.series         = self.carConditionQuery.series;
        condition.phase          = self.carConditionQuery.phase;
        condition.transmission   = txtTransmission.text;
        condition.color          = txtColor.text;
        condition.drivedirection = txtDriveDirection.text;
        condition.defect_info    = txtDefect_Info.text;
        condition.repair_info    = txtRepair_Info.text;
        condition.engine         = txtEngine.text;
        
        //todo
        self.carConditionQuery = [[Car alloc] init];
        self.carConditionQuery = condition;
        
        __weak __typeof(&*self)weakSelf = self;
        
        weakSelf.currentPage = 0;
        weakSelf.listCar = [NSMutableArray array];
        
        [self.carsTableView addPullToRefreshWithActionHandler:^{
            weakSelf.currentPage = 0;
            [weakSelf.listCar removeAllObjects];
            //todo  添加获取数据请求
            [weakSelf loadMoreData];
        }];
        [weakSelf loadMoreData];
    }
}

-(IBAction)pullDownAction:(id)sender
{
    UIButton *btn = (UIButton*)sender;
    
    _backToListBtn.hidden = NO;
    
    if (_queryViewStatus == QueryViewStatusCustom) {
        
        
        if (btn.tag == 1) {
            
            _queryStatus = QueryStatusQuickQuery;
            [_advancedQueryView removeFromSuperview];
            [self.view addSubview:_quickQueryView];
            
        }
        else if(btn.tag == 2){
            
            _queryStatus = QueryStatusAdvancedQuery;
            [_quickQueryView removeFromSuperview];
            [self.view addSubview:_advancedQueryView];
        }
        
    }else{
        if (_queryStatus == QueryStatusQuickQuery) {
            
            [UIView animateWithDuration:0.5f animations:^{
                _quickQueryView.transform = CGAffineTransformIdentity;
                
            } completion:^(BOOL finished) {
                
                _queryViewStatus = QueryViewStatusCustom;
                
                if (btn.tag == 2) {
                    _queryStatus = QueryStatusAdvancedQuery;
                    [_quickQueryView removeFromSuperview];
                    [self.view addSubview:_advancedQueryView];
                }
            }];
            
            
            
        }else{
            
            [UIView animateWithDuration:0.5f animations:^{
                _advancedQueryView.transform = CGAffineTransformIdentity;
                
            } completion:^(BOOL finished) {
                _queryViewStatus = QueryViewStatusCustom;
                
                if (btn.tag == 1) {
                    _queryStatus = QueryStatusQuickQuery;
                    [_advancedQueryView removeFromSuperview];
                    [self.view addSubview:_quickQueryView];
                }
                
            }];
        }
    }

    
//    [gAlert showLoading:nil delegate:nil];
    
    [self getListData];
    
    
}

//添加缺陷
-(void)addCarDefect:(id)sender
{
    if (self.selectedCar) {
        AddDefectViewController *vc = [[AddDefectViewController alloc] init];
        vc.selectedCar=self.selectedCar;
        [self presentViewControllerInFullRect:vc];
        
        vc.addDefect=^(Defect *newDefect){
            if (!self.selectedCar.listDefect) {
                self.selectedCar.listDefect=[NSMutableArray array];
            }
            [self.selectedCar.listDefect addObject:newDefect];
            [_defectTableView reloadData];
            
            NSMutableArray *valueArr = [NSMutableArray array];
            valueArr = [NSMutableArray arrayWithObjects:self.selectedCar.vin, nil];
            
            NSMutableArray *keyArr = [NSMutableArray array];
            keyArr   = [NSMutableArray arrayWithObjects:@"vin", nil];
            
            [gAlert showLoading:nil delegate:nil];
            
            [CommunicateWithService communicateWithService:keyArr value:valueArr apiName:@"queryVhc.do" finishSelector:@selector(changeCarFinished:) failSelector:@selector(changeCarFailed:) delegateObj:self];
        };
    }
    else
    {
        [gAlert show:@"还没有选择车辆哦" inView:self.view delegate:nil];
    }
}

-(IBAction)backToListAction:(id)sender
{
    _backToListBtn.hidden = YES;
    
    if (_queryStatus == QueryStatusQuickQuery) {
        
        
        
        //快速查
        [UIView animateWithDuration:0.5f animations:^{
            _quickQueryView.transform = CGAffineTransformMakeTranslation(0, -(_quickQueryView.frame.size.height+50));
            
        } completion:^(BOOL finished) {
            
            _queryViewStatus = QueryViewStatusTop;
        }];
    }
    else{
        //高级查询
        [UIView animateWithDuration:0.5f animations:^{
            _advancedQueryView.transform = CGAffineTransformMakeTranslation(0, -(_quickQueryView.frame.size.height+50));
            
        } completion:^(BOOL finished) {
            _queryViewStatus = QueryViewStatusTop;
            
        }];
    }
}

#pragma mark- UItableview delegate&datasource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([tableView isEqual:self.defectTableView]) {
        if (self.selectedCar) {
            return self.selectedCar.listDefect.count;
        }
        else
        {
            return 0;
        }
    }
    else
    {
        return self.listCar.count;
    }
//    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    if (tableView == self.carsTableView) {
        //车辆列表
        CarCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CarCell"];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"CarCell" owner:self options:nil] lastObject];
        }
        cell.delegate = self;
        if (self.listCar.count>0) {
            Car *cellCar=[self.listCar objectAtIndex:[indexPath row]];
            
            cell.carType.text = cellCar.seriesDesc;
//            cell.carConfig.text = cellCar.modelDesc;
            cell.carVIN.text = cellCar.vin;
            cell.carLevel.text = cellCar.level;
            cell.carTotalScore.text = cellCar.totalScore;
            
        }
        cell.tag = 10000 + indexPath.row;
        
        
        UIColor *color = [UIColor whiteColor];
        cell.selectedBackgroundView = [[UIView alloc] initWithFrame:cell.frame];
        cell.selectedBackgroundView.backgroundColor = color;
        
        return cell;
    }
    else{
        
        //缺陷列表
        DefectCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DefectCell"];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"DefectCell" owner:self options:nil] lastObject];
        }
        cell.delegate = self;
        
        [cell.line setImage:[UIImage imageNamed:@"line_defect.png"]];
        
        cell.weight.text = ((Defect *)[self.selectedCar.listDefect objectAtIndex:[indexPath row]]).weightDesc;
        
        cell.weight.backgroundColor = [GetColor getWeightColor:cell.weight.text];

        cell.title.text = ((Defect *)[self.selectedCar.listDefect objectAtIndex:[indexPath row]]).part2Desc;
        cell.defectInfo.text = ((Defect *)[self.selectedCar.listDefect objectAtIndex:[indexPath row]]).defectDesc;
        
        cell.tag = 20000 + indexPath.row;
        
        if (((Defect *)[self.selectedCar.listDefect objectAtIndex:[indexPath row]]).uploadedFile) {
            [cell.picture setImage:((Defect *)[self.selectedCar.listDefect objectAtIndex:[indexPath row]]).uploadedFile];
        }
        else
        {
            [cell.picture setImage:[UIImage imageNamed:@"defaultImg.png"]];
        }
        return cell;
        
    }
    return nil;
}

// 长按进入详情页
- (void)tableViewCellDidLongPressed:(LCSwipeTableViewCell *)cell
{
    if ([cell isKindOfClass:[CarCell class]]) {
        
        self.selectedCar = [self.listCar objectAtIndex:cell.tag-10000];
        
        CarDetailViewController *vc = [[CarDetailViewController alloc] init];
        vc.selectedCar = self.selectedCar;
        [self presentViewControllerInFullRect:vc];
    }
    else if ([cell isKindOfClass:[DefectCell class]])
    {
        self.selectedDefect = [self.selectedCar.listDefect objectAtIndex:cell.tag-20000];
        DefectDetailViewController *vc = [[DefectDetailViewController alloc] init];
        vc.selectedDefect = self.selectedDefect;
        [self presentViewControllerInFullRect:vc];
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 122;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView isEqual:self.carsTableView]) {
        
        self.selectedCar = [self.listCar objectAtIndex:[indexPath row]];
        
//        for (int i=0; i<[self.carsTableView.visibleCells count]; i++) {
//            if (i == [indexPath row]) {
//                LCSwipeTableViewCell *cell=[self.carsTableView.visibleCells objectAtIndex:[indexPath row]];
//                
//                [cell setSelected:YES];
//            }
//            else
//            {
//                LCSwipeTableViewCell *cell=[self.carsTableView.visibleCells objectAtIndex:i];
//                
//                [cell setSelected:NO];
//            }
//        }
        
//        NSMutableArray *keyArr=[NSMutableArray array];
//        NSMutableArray *valueArr=[NSMutableArray array];
        
        NSMutableArray *keyArr = [NSMutableArray arrayWithObjects:@"vehicleId" , nil];
        NSMutableArray *valueArr = [NSMutableArray arrayWithObjects:((Car *)[self.listCar objectAtIndex:[indexPath row]]).vehicleId , nil];
        
        [gAlert showLoading:nil delegate:nil];
        
        [CommunicateWithService communicateWithService:keyArr value:valueArr apiName:@"queryVhcDefect.do" finishSelector:@selector(QueryDefectFinished:) failSelector:@selector(QueryDefectFailed:) delegateObj:self];
        
        //        CarDetailViewController *vc = [[CarDetailViewController alloc] init];
        //        vc.selectedCar = self.selectedCar;
        //        [self presentViewControllerInFullRect:vc];
    }
    else
    {
        self.selectedDefect = [self.selectedCar.listDefect objectAtIndex:[indexPath row]];
    }
}

//- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
//{
//    if (tableView == _defectTableView && self.listCar.count > 0) {
//        UIView *footview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _defectTableView.frame.size.width, 130)];
//        //    footview.backgroundColor = [UIColor purpleColor];
//        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(10, 10, _defectTableView.frame.size.width-20, 120)];
//        [btn setImage:[UIImage imageNamed:@"button_add.png"] forState:UIControlStateNormal];
//        [btn addTarget:self action:@selector(addCarDefect:) forControlEvents:UIControlEventTouchUpInside];
//        [footview addSubview:btn];
//        return footview;
//    }
//    else
//    {
//        return nil;
//    }
//}

//- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
//{
//    if (tableView == _defectTableView && self.listCar.count > 0) {
//        return 180;
//    }
//    else
//    {
//        return 0;
//    }
//}


-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    UITableView *tabView = (UITableView *)scrollView;
    
    if ([tabView isEqual:_defectTableView]) {
        if (fabs(scrollView.contentOffset.y)>= _topAddDefectView.frame.size.height && scrollView.contentOffset.y<0) {
            
            if (self.selectedCar) {
                
                AddDefectViewController *vc = [[AddDefectViewController alloc] init];
                vc.selectedCar=self.selectedCar;
                [self presentViewControllerInFullRect:vc];
                
                vc.addDefect=^(Defect *newDefect){
                    if (!self.selectedCar.listDefect) {
                        self.selectedCar.listDefect=[NSMutableArray array];
                    }
                    [self.selectedCar.listDefect addObject:newDefect];
                    [_defectTableView reloadData];
                    
                    NSMutableArray *valueArr = [NSMutableArray array];
                    valueArr = [NSMutableArray arrayWithObjects:self.selectedCar.vin, nil];
                    
                    NSMutableArray *keyArr = [NSMutableArray array];
                    keyArr   = [NSMutableArray arrayWithObjects:@"vin", nil];
                    
                    [gAlert showLoading:nil delegate:nil];
                    
                    [CommunicateWithService communicateWithService:keyArr value:valueArr apiName:@"queryVhc.do" finishSelector:@selector(changeCarFinished:) failSelector:@selector(changeCarFailed:) delegateObj:self];
                };
            }
            else
            {
                [gAlert show:@"还没有选择车辆哦" delegate:nil];
            }
        }
    }
}

#pragma mark LCSwipeTableViewCellDelegate

- (void)tableViewCell:(LCSwipeTableViewCell *)cell didTriggerRightUtilityButtonWithIndex:(NSInteger)index {
    if ([cell isKindOfClass:[CarCell class]]) {
        
        Car *cellCar =[self.listCar objectAtIndex:cell.tag-10000];
        
        self.editCar = cellCar;
        
        //车辆列表
        switch (index) {
            case 0:
            {
                //编辑
                AddCarViewController *vc=[[AddCarViewController alloc] init];
                vc.doSth = @"edit";
                vc.currentCar = cellCar;
                [self presentViewControllerInFullRect:vc];
                
                __block int selectedIndex = 0;
                
                vc.editCar=^(Car *editCar){
                    for (int i=0;i<self.listCar.count;i++) {
                        if ([((Car *)[self.listCar objectAtIndex:i]).vehicleId isEqualToString:editCar.vehicleId]) {
                            [self.listCar removeObjectAtIndex:i];
                            [self.listCar insertObject:editCar atIndex:i];
                            selectedIndex = i;
                            break;
                        }
                    }
                    [_carsTableView reloadData];
                    
                    [_carsTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:selectedIndex inSection:0] animated:YES scrollPosition:UITableViewScrollPositionNone];
                    
                    self.selectedCar = [self.listCar objectAtIndex:selectedIndex];
                    if (!self.selectedCar.listDefect) {
                        NSMutableArray *keyArr=[NSMutableArray array];
                        NSMutableArray *valueArr=[NSMutableArray array];
                        
                        keyArr = [NSMutableArray arrayWithObjects:@"vehicleId" , nil];
                        valueArr = [NSMutableArray arrayWithObjects:self.editCar.vehicleId , nil];
                        
                        [gAlert showLoading:nil delegate:nil];
                        
                        [CommunicateWithService communicateWithService:keyArr value:valueArr apiName:@"queryVhcDefect.do" finishSelector:@selector(QueryDefectFinished:) failSelector:@selector(QueryDefectFailed:) delegateObj:self];
                    }
                    else
                    {
                        [_defectTableView reloadData];
                    }
                };
            }
                break;
            case 1:
            {
                //删除
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"确认删除吗？" preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                    
                }];
                
                UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"删除" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                    //删除
//                    NSLog(@"删除车辆。。。。\n");
                    NSArray *keyArr   = [NSArray arrayWithObjects:@"vehicleId",nil];
                    NSArray *valueArr = [NSArray arrayWithObjects:self.editCar.vehicleId,nil];
                    
                    [gAlert showLoading:nil delegate:nil];
                    [CommunicateWithService communicateWithService:keyArr value:valueArr apiName:@"vhcDelete.do" finishSelector:@selector(deleteCarFinished:) failSelector:@selector(deleteCarFailed:) delegateObj:self];
                    
                }];
                [alertController addAction:cancelAction];
                [alertController addAction:okAction];
                
                
                [self presentViewController:alertController animated:YES completion:nil];
//                
//                UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示" message:@"确认删除吗？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
//                alert.tag=101;
//                [alert show];
            }
                break;
            default:
                break;
        }
    }
    else if ([cell isKindOfClass:[DefectCell class]])
    {
        Defect *cellDefect =[self.selectedCar.listDefect objectAtIndex:cell.tag-20000];
        
        self.editDefect = cellDefect;
        
        switch (index) {
            case 0:
            {
                //编辑
                AddDefectViewController *vc=[[AddDefectViewController alloc] init];
                vc.isFirst = YES;
                vc.doSth=@"edit";
                vc.currentDefect=cellDefect;
                vc.selectedCar=self.selectedCar;
                [self presentViewControllerInFullRect:vc];
                
                vc.editDefect=^(Defect *editDefect){
                    for (int i=0;i<self.selectedCar.listDefect.count;i++) {
                        if ([((Defect *)[self.selectedCar.listDefect objectAtIndex:i]).auditId isEqualToString:editDefect.auditId]) {
                            [self.selectedCar.listDefect removeObjectAtIndex:i];
                            [self.selectedCar.listDefect insertObject:editDefect atIndex:i];
                            break;
                        }
                    }
                    [_defectTableView reloadData];
                    
                    NSMutableArray *valueArr = [NSMutableArray array];
                    valueArr = [NSMutableArray arrayWithObjects:self.selectedCar.vin, nil];
                    
                    NSMutableArray *keyArr = [NSMutableArray array];
                    keyArr   = [NSMutableArray arrayWithObjects:@"vin", nil];
                    
                    [gAlert showLoading:nil delegate:nil];
                    
                    [CommunicateWithService communicateWithService:keyArr value:valueArr apiName:@"queryVhc.do" finishSelector:@selector(changeCarFinished:) failSelector:@selector(changeCarFailed:) delegateObj:self];
                };
            }
                break;
            case 1:
            {
                //删除
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"确认删除吗？" preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                    
                }];
                
                UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"删除" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                    //删除
                    
                    NSArray *keyArr   = [NSArray arrayWithObjects:@"auditId",nil];
                    NSArray *valueArr = [NSArray arrayWithObjects:self.editDefect.auditId,nil];
                    
                    [gAlert showLoading:nil delegate:nil];
                    [CommunicateWithService communicateWithService:keyArr value:valueArr apiName:@"vhcDefectDelete.do" finishSelector:@selector(deleteDefectFinished:) failSelector:@selector(deleteDefectFailed:) delegateObj:self];
                    
                }];
                [alertController addAction:cancelAction];
                [alertController addAction:okAction];
                
                
                [self presentViewController:alertController animated:YES completion:nil];
                
//                UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示" message:@"确认删除吗？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
//                alert.tag=102;
//                [alert show];
            }
                break;
            default:
                break;
        }
    }
}

- (BOOL)tableViewCellShouldHideUtilityButtonsOnSwipe:(LCSwipeTableViewCell *)cell {
    return YES;
}

-(void)deleteCarFinished:(ASIHTTPRequest *)request
{
    [gAlert dismiss];
    if (request.responseStatusCode == 400) {
        //textView.text = @"Invalid code";
        NSLog(@"Invalid code");
    } else if (request.responseStatusCode == 403) {
        NSLog(@"Code already used");
        //textView.text = @"Code already used";
    } else if (request.responseStatusCode == 200) {
        for (int i=0;i<self.listCar.count;i++) {
            NSDictionary *strDic=[CommunicateWithService getDataDic:request.responseString];//解析json 2 dic
            
            NSString *flag=[strDic objectForKey:@"resultCode"];//服务器返回代码
            
            NSString *msg=[strDic objectForKey:@"resultValue"];//服务器返回提示消息
            
//            NSDictionary *strDicData=(NSDictionary *)[strDic objectForKey:@"resultData"];//服务器返回数据字典
            
            if ([flag isEqualToString:@"1001"]) {
                for (int i=0;i<self.listCar.count;i++) {
                    if ([((Car *)[self.listCar objectAtIndex:i]).vehicleId isEqualToString:self.editCar.vehicleId]) {
                        [self.listCar removeObjectAtIndex:i];
                        break;
                    }
                }
                [_carsTableView reloadData];
                
                if (self.listCar.count > 0) {
                    if ([self.editCar isEqual:self.selectedCar])
                    {
                        self.selectedCar = (Car *)[self.listCar objectAtIndex:0];
                        
                        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
                        
                        [_carsTableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionTop];
                        
                        NSMutableArray *keyArr = [NSMutableArray arrayWithObjects:@"vehicleId" , nil];
                        NSMutableArray *valueArr = [NSMutableArray arrayWithObjects:self.selectedCar.vehicleId , nil];
                        
                        [gAlert showLoading:nil delegate:nil];
                        
                        [CommunicateWithService communicateWithService:keyArr value:valueArr apiName:@"queryVhcDefect.do" finishSelector:@selector(QueryDefectFinished:) failSelector:@selector(QueryDefectFailed:) delegateObj:self];
                    }
                    else
                    {
                        for (int i=0;i<self.listCar.count;i++) {
                            if ([((Car *)[self.listCar objectAtIndex:i]).vehicleId isEqualToString:self.selectedCar.vehicleId]) {
                                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
                                
                                [_carsTableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionTop];
                                break;
                            }
                        }
                    }
                }
                else
                {
                    self.selectedCar = nil;
                    
                    [_defectTableView reloadData];
                }
            }
            else if ([flag isEqualToString:@"1002"])
            {
                [gAlert show:msg inView:self.view delegate:nil];
            }
        }
    }
}

-(void)deleteCarFailed:(ASIHTTPRequest *)request
{
    [gAlert dismiss];
    [NetworkCheck checkNetwork:self];
}

-(void)deleteDefectFinished:(ASIHTTPRequest *)request
{
    [gAlert dismiss];
    if (request.responseStatusCode == 400) {
        //textView.text = @"Invalid code";
        NSLog(@"Invalid code");
    } else if (request.responseStatusCode == 403) {
        NSLog(@"Code already used");
        //textView.text = @"Code already used";
    } else if (request.responseStatusCode == 200) {
        for (int i=0;i<self.listCar.count;i++) {
            NSDictionary *strDic=[CommunicateWithService getDataDic:request.responseString];//解析json 2 dic
            
            NSString *flag=[strDic objectForKey:@"resultCode"];//服务器返回代码
            
            NSString *msg=[strDic objectForKey:@"resultValue"];//服务器返回提示消息
            
//            NSDictionary *strDicData=(NSDictionary *)[strDic objectForKey:@"resultData"];//服务器返回数据字典
            
            if ([flag isEqualToString:@"1001"]) {
                for (int i=0;i<self.selectedCar.listDefect.count;i++) {
                    if ([((Defect *)[self.selectedCar.listDefect objectAtIndex:i]).auditId isEqualToString:self.editDefect.auditId]) {
                        [self.selectedCar.listDefect removeObjectAtIndex:i];
                        break;
                    }
                }
                [_defectTableView reloadData];
                
                NSMutableArray *valueArr = [NSMutableArray array];
                valueArr = [NSMutableArray arrayWithObjects:self.selectedCar.vin, nil];
                
                NSMutableArray *keyArr = [NSMutableArray array];
                keyArr   = [NSMutableArray arrayWithObjects:@"vin", nil];
                
                [gAlert showLoading:nil delegate:nil];
                
                [CommunicateWithService communicateWithService:keyArr value:valueArr apiName:@"queryVhc.do" finishSelector:@selector(changeCarFinished:) failSelector:@selector(changeCarFailed:) delegateObj:self];
            }
            else if ([flag isEqualToString:@"1002"])
            {
                
                [gAlert show:msg inView:self.view delegate:nil];
            }
        }
    }
}

-(void)deleteDefectFailed:(ASIHTTPRequest *)request
{
    [gAlert dismiss];
    [NetworkCheck checkNetwork:self];
}

-(void)changeCarFinished:(ASIHTTPRequest *)request
{
    [gAlert dismiss];
    if (request.responseStatusCode == 400) {
        //textView.text = @"Invalid code";
        NSLog(@"Invalid code");
    } else if (request.responseStatusCode == 403) {
        NSLog(@"Code already used");
        //textView.text = @"Code already used";
    } else if (request.responseStatusCode == 200) {
        NSDictionary *strDic=[CommunicateWithService getDataDic:request.responseString];//解析json 2 dic
        
        //        NSLog(@"%@",request.responseString);
        
        NSString *flag=[strDic objectForKey:@"resultCode"];//服务器返回代码
        
        NSString *msg=[strDic objectForKey:@"resultValue"];//服务器返回提示消息
        
        NSDictionary *strDicData=(NSDictionary *)[strDic objectForKey:@"resultData"];//服务器返回数据字典
        
        //        self.tableDataList = [NSMutableArray array];
        
        if ([flag isEqualToString:@"1001"]) {
            NSArray *carList = [strDicData objectForKey:@"content"];
            
            if (carList.count == 1) {
                Car * getCar = [[Car alloc] initWithInfo:(NSDictionary *)[carList objectAtIndex:0]];
                
                getCar.listDefect = [NSMutableArray array];
                
                getCar.listDefect = [NSMutableArray arrayWithArray:self.selectedCar.listDefect];
                
                for (int i = 0 ; i < self.listCar.count; i++) {
                    if ([self.selectedCar.vin isEqualToString:((Car *)[self.listCar objectAtIndex:i]).vin]) {
                         [self.listCar replaceObjectAtIndex:i withObject:getCar];
                        [_carsTableView reloadData];
                        
                        [_carsTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]  animated:NO scrollPosition:UITableViewScrollPositionNone];
                        
                        break;
                    }
                }
            }
        }
        else if ([flag isEqualToString:@"1002"])
        {
            
            [gAlert show:msg inView:self.view delegate:nil];
        }
    }
}

-(void)changeCarFailed:(ASIHTTPRequest *)request
{
    [gAlert dismiss];
    //    [self hideWaitFromView:self.view animated:YES];
    [NetworkCheck checkNetwork:self];
}

//IOS7
#pragma mark - alert
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag==101) {
        if (buttonIndex==1) {
            NSArray *keyArr   = [NSArray arrayWithObjects:@"vehicleId",nil];
            NSArray *valueArr = [NSArray arrayWithObjects:self.selectedCar.vehicleId,nil];

//            [gAlert showLoading:nil delegate:nil];
            [CommunicateWithService communicateWithService:keyArr value:valueArr apiName:@"vhcDelete.do" finishSelector:@selector(deleteCarFinished:) failSelector:@selector(deleteCarFailed:) delegateObj:self];
        }
    }
    else
    {
        if (buttonIndex==1) {
            NSArray *keyArr   = [NSArray arrayWithObjects:@"auditId",nil];
            NSArray *valueArr = [NSArray arrayWithObjects:self.selectedDefect.auditId,nil];
            
//            [gAlert showLoading:nil delegate:nil];
            [CommunicateWithService communicateWithService:keyArr value:valueArr apiName:@"vhcDefectDelete.do" finishSelector:@selector(deleteDefectFinished:) failSelector:@selector(deleteDefectFailed:) delegateObj:self];
        }
    }
}

#pragma mark - UITextField Delegate
- (void)keyboardWasShown:(NSNotification*)aNotification
{
    if (_selectedTxt!= txtVin && _selectedTxt!=txtBuildDate && _selectedTxt!=txtShiftDate) {
        [UIView animateWithDuration:.8f animations:^{
            if (_queryStatus  == QueryStatusAdvancedQuery) {
                _advancedQueryView.transform = CGAffineTransformMakeTranslation(0,-240);
            }
        }];
    }
}

- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    [UIView animateWithDuration:.5f animations:^{
        if (_queryStatus  == QueryStatusAdvancedQuery) {
            _advancedQueryView.transform = CGAffineTransformIdentity;
        }
        
    }];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if(textField.returnKeyType == UIReturnKeyNext){
        if (self.selectedTxt == textFieldVIN) {
            [textFieldCsn becomeFirstResponder];
        }
        else
        {
            [textField resignFirstResponder];
        }
    }
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    _selectedTxt = textField;
    
    [textField becomeFirstResponder];
    
//    if (textField != txtVin && textField!=txtBuildDate && textField!=txtShiftDate) {
//        
////        [UIView animateWithDuration:.8f animations:^{
//            if (_queryStatus  == QueryStatusAdvancedQuery) {
//                _advancedQueryView.transform = CGAffineTransformMakeTranslation(0,-220);
//            }
//            
////        }];
//        
//    }
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [textField resignFirstResponder];
////    [UIView animateWithDuration:.5f animations:^{
//        if (_queryStatus  == QueryStatusAdvancedQuery) {
//            _advancedQueryView.transform = CGAffineTransformIdentity;
//        }
//        
////    }];
    
}

- (void)textChange:(UITextField *)textField
{
    textField.text = [textField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    if (textField.text.length>17) {
        textField.text = [textField.text substringToIndex:17];
        
        
        [gAlert show:@"VIN号不能超过17位噢" inView:self.view delegate:nil];
    }
    
    textField.text = [textField.text uppercaseString];
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [txtVin resignFirstResponder];//VIN
    [txtTransmission resignFirstResponder];//变
    [txtColor resignFirstResponder];//颜色
    [txtDriveDirection resignFirstResponder];
    [txtDefect_Info resignFirstResponder];//重
    [txtRepair_Info resignFirstResponder];//返
    [txtEngine resignFirstResponder];
    [txtShiftDate  resignFirstResponder];
    [txtBuildDate resignFirstResponder];
    [txtCsn  resignFirstResponder];//生
}

@end
